﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
using SushiRESTServicesTest.Dominio;
using SushiRESTServicesTest.Exception;

namespace SushiRESTServicesTest
{
    [TestClass]
    public class PersonasRESTServicesTest
    {
        [TestMethod]
        public void CrearPersonaTest()
        {
          
            string postdata0 = "{\"IdPersona\":12,\"TipoDocIden\":\"DNI\",\"NumDocIden\":\"2223553\",\"Nombres\":\"Juan\",\"Apellidos\":\"Perez\",\"FecNacimiento\":\"2013-04-02\",\"Telefono\":\"12312312\",\"Direccion\":\"jr alamos 123\",\"Email\":\"asd@fdacom\",\"TipoPersona\":\"CLNTE\"}";
            
            //Prueba de creación de alumno vía HTTP POST
            byte[] data = Encoding.UTF8.GetBytes(postdata0);
            HttpWebRequest req = (HttpWebRequest)WebRequest
                .Create("http://localhost:47850/Personas.svc/Personas");
            req.Method = "POST";
            req.ContentLength = data.Length;
            req.ContentType = "application/json";
            var reqStream = req.GetRequestStream();
            reqStream.Write(data, 0, data.Length);

            HttpWebResponse res = null;
            try
            {

                res = (HttpWebResponse)req.GetResponse();
                StreamReader reader = new StreamReader(res.GetResponseStream());
                string unidadJson = reader.ReadToEnd();
                JavaScriptSerializer js = new JavaScriptSerializer();
                Persona personaCreada = js.Deserialize<Persona>(unidadJson);
                Assert.AreEqual("2223553", personaCreada.NumDocIden);
                Assert.AreEqual("12312312", personaCreada.Telefono);
                Assert.AreEqual("Juan", personaCreada.Nombres);
                Assert.AreEqual("Perez", personaCreada.Apellidos);

            }
           catch (WebException ex)
            {

                // Mostrar Error 
                HttpWebResponse resError = (HttpWebResponse)ex.Response;
                StreamReader reader2 = new StreamReader(resError.GetResponseStream());
                string error = reader2.ReadToEnd();
                JavaScriptSerializer js = new JavaScriptSerializer();
                PersonaException exception = js.Deserialize<PersonaException>(error);
                Assert.AreEqual("El D.N.I. ingresado ya existe", exception.Message);
            }
        }
    }
}
